package com.sskj.mine.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.allen.library.SuperTextView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.LanguageUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.BottomSheetUtil;
import com.sskj.lib.util.CommonUtil;
import com.sskj.mine.BuildConfig;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.presenter.SettingPresenter;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 *设置
 */
@Route(path = RConfig.MINE_SETTING)
public class SettingActivity extends BaseActivity<SettingPresenter> {


    @BindView(R2.id.menu_language)
    SuperTextView menuLanguage;
    @BindView(R2.id.menu_version)
    SuperTextView menuVersion;


    private final int SELECT_HEAD = 1005;
    private String path;

    BottomSheetDialog dialog;
    View dialogView;
    TextView action1;
    TextView action2;
    TextView cancel;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private BottomSheetDialog bottomSheet;
    private Disposable languageDispo;

    @Override
    public int getLayoutId() {
        return R.layout.mine_activity_setting;
    }

    @Override
    public SettingPresenter getPresenter() {
        return new SettingPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        setTitle(App.INSTANCE.getString(R.string.mine_settingActivity1));
        menuLanguage.setRightString(CommonUtil.dealLanguage(LanguageUtil.getAppLocale(App.INSTANCE).toString()));
    }

    @Override
    protected void initEvent() {
        ClickUtil.click(menuLanguage, this::selectLanguage);

    }

    private void showSelectDialog() {
        initDialog();
        dialog.show();
        action1 = dialogView.findViewById(R.id.dialog_take_photo);
        action2 = dialogView.findViewById(R.id.dialog_select_photo);
        cancel = dialogView.findViewById(R.id.dialog_cancel);
        action1.setText(App.INSTANCE.getString(R.string.mine_settingActivity2));
        action2.setText(App.INSTANCE.getString(R.string.mine_settingActivity3));
        action1.setOnClickListener(view -> {
            selectPhoto(true);
            dialog.dismiss();
        });
        action2.setOnClickListener(view -> {
            selectPhoto(false);
            dialog.dismiss();
        });
        cancel.setOnClickListener(view -> dialog.dismiss());
    }

    private void initDialog() {
        if (dialog == null) {
            dialogView = LayoutInflater.from(this).inflate(R.layout.mine_dialog_slect_head, null);
            dialog = new BottomSheetDialog(this);
            dialog.setContentView(dialogView);
        }
    }


    private void selectLanguage() {
        languageDispo = Flowable.fromIterable(LanguageUtil.locales)
                .map(locale -> CommonUtil.dealLanguage(locale.toString()))
                .toList()
                .subscribe((strings, throwable) -> {
                    bottomSheet = BottomSheetUtil.getBottomSheet(this, null, (recyclerView, position, view) -> {
                        bottomSheet.dismiss();
                        changeLanguage(LanguageUtil.getAppLocaleByToString(CommonUtil.rdealLanguage(strings.get(position))));
                    }, strings);
                    bottomSheet.show();
                });
    }

    private void changeLanguage(Locale locale) {

        LanguageUtil.saveLanguageSetting(App.INSTANCE, locale);
        RxBus.getDefault().send(RxBusCode.CHANGE_LANGUAGE);

    }


    @SuppressLint("CheckResult")
    private void selectPhoto(boolean isCamera) {
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) {
                        if (isCamera) {
                            PictureSelector.create(this)
                                    .openCamera(PictureMimeType.ofImage())
                                    .maxSelectNum(1)
                                    .compress(true)
                                    .forResult(SELECT_HEAD);
                        } else {
                            PictureSelector.create(this)
                                    .openGallery(PictureMimeType.ofImage())
                                    .isCamera(false)
                                    .maxSelectNum(1)
                                    .compress(true)
                                    .forResult(SELECT_HEAD);
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_HEAD) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList != null && selectList.size() > 0) {
                    LocalMedia media = selectList.get(0);
                    String url;
                    if (media.isCompressed()) {
                        url = media.getCompressPath();
                    } else {
                        url = media.getPath();
                    }
                    path = url;
                    //TODO: 还没有上传
                    mPresenter.submitVerify(new File(path));
                }
            }
        }
    }


    @Override
    public void initData() {
        String versionName = BuildConfig.VERSION_NAME;
        menuVersion.setRightString("V" + versionName);
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, SettingActivity.class);
        context.startActivity(intent);
    }

    public void updateUi() {
        userViewModel.update();
    }

    @Override
    protected void onResume() {
        super.onResume();
        userViewModel.update();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DisposUtil.close(languageDispo);
        RxBus.getDefault().unregister(this);
    }
}
